﻿using WebApp.BLL;
using WebApp.Web.Core.Auth;
using WebApp.BLL.Manage;
using WebApp.Common;
using WebApp.Models;
using WebApp.ViewModels;
using WebApp.ViewModels.Manage;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApp.Web.Core;

namespace kzjd.rycp.WebApp.Areas.Manage.Controllers
{
    public class RoleController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        // GET: Manage/Role
        [AuthorizeFilter("Manage.Role")]
        public ActionResult List()
        {
            ////权限（查看/编辑）
            //ViewBag.Actions = "E";
            //菜单图标
            ViewBag.NavIcon = new S_menuService().GetMenuIconByAction();

            //编辑权限
            ViewBag.CanEdit = UserAuthBLL.HasAuth("Manage.Role.Edit");

            //获取页面状态
            var pageState = Session["Study.Setting.PageState"] as PageStateModel;
            if (pageState == null)
                pageState = new PageStateModel
                {
                    page = 1,
                    rows = 20,
                    sort = "Id",
                    order = "asc"
                };

            //var custcode = string.IsNullOrEmpty(Utils.NvStr(pageState.queryParams["custcode"])) ? SessionManage.Custcode : pageState.queryParams["custcode"].ToString();
            //页面状态
            ViewBag.PageState = pageState;

            ////当前客户信息
            //ViewBag.Custcode = custcode;
            //ViewBag.Custname = new S_customerService().GetName(custcode);
            //查询条件
            ViewBag.Searchkey = Utils.NvStr(pageState.queryParams["s"]);

            ////角色库/客户自定义角色
            //ViewBag.RoletypeList = new SelectList(Utils.EnumToList(typeof(enmRoletype)), "Key", "Value");

            return View();
        }
        // GET: Manage/Role
        [AuthorizeFilter("Manage.Role")]
        public ActionResult RoleUser(string id)
        {
            //菜单图标
            ViewBag.NavIcon = new S_menuService().GetMenuIconByAction();
            //编辑权限
            ViewBag.CanEdit = UserAuthBLL.HasAuth("Master.User.Edit");
            //角色CODE
            ViewBag.Roleid = id;
            return View();
        }

        #region 查询角色列表数据

        [AuthorizeFilter("Manage.Role")]
        public JsonResult RoleListJson(int page, int rows, string s, string sort, string order)
        {
            S_roleService roleservice = new S_roleService();
            //S_customerService customerService = new S_customerService();
            Dictionary<string, object> result = new Dictionary<string, object>();

            int rowscount = 0;

            var list = roleservice.PageList(page, rows, s, sort, order, out rowscount).Select(p => new
            {
                p.Id,
                p.Roleid,
                p.Rolename,
                p.Description,
                p.Isdeleted
            });

            result.Add("total", rowscount);
            result.Add("rows", list);

            return Json(result);
        }

        #endregion

        #region 删除

        [AuthorizeFilter("Manage.Role.Edit")]
        public JsonResult Delete(string ids)
        {
            try
            {
                new S_roleService().DeleteByIds(ids);

                return Json(new AjaxResult("0", CSMSLang.Get("message_delete_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 保存

        [AuthorizeFilter("Manage.Role.Edit")]
        public JsonResult Save(string jsondata)
        {
            try
            {
                S_roleService roleservice = new S_roleService();

                //序列化Json数据
                JsonDataModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonDataModel>(jsondata);

                S_role role = new S_role();
                if (model.Id > 0)
                {
                    role = roleservice.Find(model.Id);
                }
                role.Isdeleted = "0";
                //通过反射给属性赋值
                model.SetModelData<S_role>(role, true);

                //保存
                roleservice.Save(role);

                return Json(new AjaxResult(AjaxResult.RESULT_OK, CSMSLang.Get("message_save_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }



        #endregion

        #region 编辑/查看

        [AuthorizeFilter("Manage.Role.Edit")]
        // GET: Manage/Role/Edit/5
        public ActionResult Edit(int id)
        {
            if (id == 0)
            {
                return View(new S_role()
                {
                    Isdeleted = "0"
                });
            }
            else
            {

                S_role item = new S_roleService().Find(id);

                if (item == null)
                {
                    throw new HttpException(404, "Role(id='" + id.ToString() + "') not found!");
                }
                return View(item);
            }
        }

        // GET: Manage/Role/Details/5
        [AuthorizeFilter("Manage.Role.Details")]
        public ActionResult Details(int id)
        {
            S_role item = new S_roleService().Find(id);
            if (item == null)
            {
                throw new HttpException(404, "Role(id='" + id.ToString() + "') not found!");
            }
            return View(item);
        }

        #endregion

        #region 重复验证
        [IgnoreAuthorizeFilter]
        public string ExsitCheck(int id, string roleid)
        {
            return new S_roleService().Exist(id, roleid) ? "no" : "yes";
        }

        #endregion

        #region 菜单权限

        [IgnoreAuthorizeFilter]
        public ActionResult RoleMenu(int id)
        {
            //角色信息
            S_role role = new S_roleService().Find(id);
            if (role == null)
            {
                throw new HttpException(404, "Role(id='" + id.ToString() + "') not found!");
            }

            //角色已经设置的菜单
            var rolemenuList = new S_role_menuService().FindAllRoleid(role.Roleid);

            //菜单树结构
            new S_menuService().ClearCache();
            var menutrees = this.BuildRoleMenuTreeList(rolemenuList, "");

            ViewBag.Menualljson = System.Web.Helpers.Json.Encode(menutrees).Replace("_ischecked", "checked");

            return View(role);
        }

        public List<PublicEasyuiTreeModel> BuildRoleMenuTreeList(List<S_role_menu> rolemenus, string pmenuid)
        {
            S_menuService menuService = new S_menuService();

            var menulist = menuService.GetPmenuid(pmenuid).Select(p => new PublicEasyuiTreeModel
            {
                id = p.Menuid,
                text = p.Menuname_zho,
                _ischecked = rolemenus.Any(r => r.Menuid == p.Menuid),
                state = p.Menukind == enmMenuKind.模块.ToString("d") ? "opened" : "closed",
                iconCls = p.Menukind == enmMenuKind.模块.ToString("d") ? "" : (p.Menukind == enmMenuKind.菜单.ToString("d") ? "" : ""),
                children = this.BuildRoleMenuTreeList(rolemenus, p.Menuid)
            }).ToList();

            foreach (var item in menulist)
            {
                if (item.children.Count > 0)
                {
                    item._ischecked = false;
                }
            }

            return menulist;
        }

        /// <summary>
        /// 保存菜单权限
        /// </summary>
        /// <param name="jsondata"></param>
        /// <returns></returns>
        [IgnoreAuthorizeFilter]
        public JsonResult RolemenuSave(string jsondata)
        {
            try
            {
                S_roleService roleService = new S_roleService();
                S_role_menuService rolemenuService = new S_role_menuService();
                RoleMenuModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<RoleMenuModel>(jsondata);
                rolemenuService.Save(model.roleid, model.menuids);

                return Json(new AjaxResult(AjaxResult.RESULT_OK, CSMSLang.Get("message_save_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }
        #endregion
    }
}